package com.predic8.membrane.servlet;

import com.predic8.membrane.servlet.embedded.HttpServletHandler;
import com.google.common.collect.Lists;
import com.predic8.membrane.core.resolver.ResourceRetrievalException;
import com.predic8.membrane.core.resolver.SchemaResolver;
import com.predic8.membrane.core.util.functionalInterfaces.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import java.io.InputStream;
import java.util.List;

public class FileSchemaWebAppResolver implements SchemaResolver {

    private static Logger logger =  LoggerFactory.getLogger(HttpServletHandler.class);

    private final ServletContext ctx;

    public FileSchemaWebAppResolver(ServletContext ctx) {
        this.ctx = ctx;
    }

    public ServletContext getCtx() {
        return ctx;
    }

    @Override
    public List<String> getSchemas() {
        return Lists.newArrayList("file", null);
    }

    @Override
    public InputStream resolve(String url) throws ResourceRetrievalException {
        if (url.startsWith("file:"))
            url = url.substring(5);
        logger.debug("loading resource from: " + url);
        InputStream is = ctx.getResourceAsStream(url);
        if (is == null)
            throw new ResourceRetrievalException(url);
        return is;
    }

    @Override
    public void observeChange(String url, Consumer<InputStream> consumer) throws ResourceRetrievalException {
        throw new RuntimeException("Not implemented");
    }

    @Override
    public List<String> getChildren(String url) {
        return null;
    }

    @Override
    public long getTimestamp(String url) {
        return 0;
    }

}
